package com.huanglejing.shanggou.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v4.util.ArrayMap
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.View
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.adapter.ProductListAdapter
import com.huanglejing.shanggou.bean.GoodsListBean
import com.huanglejing.shanggou.bean.NewComeProBean
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.data.*
import com.huanglejing.shanggou.greendao.CacheGoodsBean
import com.huanglejing.shanggou.greendao.CacheGoodsBeanDao
import com.huanglejing.shanggou.interfaces.ProductListContract.ProductListPresenter
import com.huanglejing.shanggou.interfaces.ProductListContract.ProductListView
import com.huanglejing.shanggou.presenterimpl.ProductListImpl
import com.huanglejing.shanggou.utils.UIHelper
import com.huanglejing.shanggou.utils.checkEmpty
import com.huanglejing.shanggou.utils.fromJson
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.rtdl.dropdownmenu.TwoMenuHolder
import kotlinx.android.synthetic.main.activity_product_list.*
import rx.Observable
import android.support.v4.view.ViewCompat.getMinimumHeight
import android.support.v4.view.ViewCompat.getMinimumWidth
import android.graphics.drawable.Drawable




class ProductListActivity : AppBaseActivity<ProductListPresenter<ProductListView>, ProductListView>(), ProductListView, XRecyclerView.LoadingListener {
    private var mData: ArrayList<NewComeProBean>? = arrayListOf()
    private var mBackData: ArrayList<NewComeProBean>? = null
    private var leftPosion = 0
    private var cacheLeftPosion = 0
    private var rightPosion = 0
    private var cacheRightPosion = 0
    // private var smoothPosition = 0
    private var mDataLeft: ArrayList<GoodsListBean>? = arrayListOf()
    private var mDataRight: ArrayList<ArrayList<GoodsListBean>>? = arrayListOf()
    private var mNextAdapter: ProductListAdapter? = null
    private var categoryId = ""
    private var bundleCategoryId = ""
    private var initCategoryId = ""
    private var isLoadMoreFinish = true
    private var isComeplete = false
    private var isRefrsesh = false
    private var isRefreshFinishComplete = true
    private var loadMoreText = ""
    private var refreshTextText = ""

    private val mEmptyView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_empty)
    }
    private val mErrorView by lazy {
        mRootView?.findViewById<View>(R.id.ll_xr_error)
    }

    private val menu by lazy {
        TwoMenuHolder(this@ProductListActivity, getCacheGoodsImgs() ?: arrayListOf(), { t1, t2 ->
        }, { view, i, i1 ->
            leftPosion = i
            rightPosion = i1
            if (leftPosion == mDataLeft?.size?.minus(1)
                    && rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                isComeplete = true
            } else {
                isComeplete = false
            }
            categoryId = mDataRight?.getOrNull(i)?.getOrNull(i1)?.guid ?: ""
            mNextAdapter?.setCacheData(getCacheGoods()?.filter {
                it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
            })
            if (mBackData != null) {
                showContent(mBackData)
                mBackData = null
            } else {
                mBasePresenter?.getProductList()
            }
            xr_toolbar_list?.scrollToPosition(0)
            //  mNextAdapter?.notifyDataSetChanged()
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bundleCategoryId = intent?.extras?.getString("categoryId") ?: ""
        initWidget()
    }


    override fun createPresenter(): ProductListPresenter<ProductListView> = ProductListImpl()

    override fun getLayoutId(): Int = R.layout.activity_product_list

    override fun requestPermission() {
    }


    private fun initWidget() {
        setAPPTitle("")
        iv_search?.setOnClickListener {
            UIHelper.startActivity(SearchActivity::class.java)
        }
        iv_buy_car?.setOnClickListener {
            val intent = Intent(this@ProductListActivity, CurrentOrderActivity::class.java)
            intent?.putExtra("requestCode", 300)
            startActivityForResult(intent, 300)
        }

        bt_my_title.setOnClickListener {
            menu.TopTapClick()
            if (menu.isMenuOpen){
              //  bt_my_title.setTextColor(Color.parseColor("#ED3009"))
                val drawable = resources.getDrawable(R.drawable.ic_arrow_up)
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                bt_my_title.setCompoundDrawables(null, null, drawable, null)
            }else{
              //  bt_my_title.setTextColor(Color.parseColor("#111111"))
                val drawable = resources.getDrawable(R.drawable.ic_arrow_down_red)
                /// 这一步必须要做,否则不会显示.
                drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
                bt_my_title.setCompoundDrawables(null, null, drawable, null)
            }
        }
        xr_toolbar_list?.setPullRefreshEnabled(true)
        xr_toolbar_list?.setLoadingMoreEnabled(true)
        xr_toolbar_list?.setLoadingListener(this)
        //设置加载风格
        xr_toolbar_list?.setLoadingMoreProgressStyle(ProgressStyle.LineScale)
        xr_toolbar_list?.setRefreshProgressStyle(ProgressStyle.BallGridPulse)

        val manager = GridLayoutManager(this@ProductListActivity, 2)
        xr_toolbar_list?.layoutManager = manager
        mNextAdapter = ProductListAdapter(this@ProductListActivity, mData ?: arrayListOf())
        xr_toolbar_list?.adapter = mNextAdapter
        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        //   mNextAdapter?.setCacheData(loadAll)
        mNextAdapter?.setOnItemClickListener(object : ProductListAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                val intent = Intent(this@ProductListActivity, ProListDetailActivity::class.java)
                val bundle = Bundle()
                bundle.putString("categoryId", mData?.get(position)?.parentGuid)
                bundle.putInt("position", position)
                bundle.putInt("leftPosion", leftPosion)
                bundle.putInt("rightPosion", rightPosion)
                bundle.putBoolean("isNeedBack", true)
                bundle.putString("mBundleData", AppContext.gson().toJson(mData))
                intent.putExtras(bundle)
                startActivityForResult(intent, 100)
            }
        })
        mNextAdapter?.setCacheOrderBeanListener(object : ProductListAdapter.CacheOrderBeanListener {
            override fun onCacheOrderBeanAdd(position: Int, selectNum: Int, bean: NewComeProBean?) {
                var loadAll = getCacheGoods()?.filter {
                    it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
                }
                var isUpdate = false
                var updateBean: CacheGoodsBean? = null
                loadAll?.forEachIndexed { index, orderBean ->
                    if (orderBean?.goodNO?.equals(bean?.id ?: "") ?: false) {
                        isUpdate = true
                        updateBean = orderBean
                    }
                }
                if (isUpdate && updateBean != null) {
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = updateBean?.bz ?: ""
                    updateBean?.categoryGUID = categoryId ?: ""
                    updateBean?.num = selectNum?.div(bean?.bagCount?.toIntOrNull()?:1)?.toString()?:"0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    val zhekou = bean?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.times(1.minus(zhekou))?.toString() ?: ""
                    beanDao?.update(updateBean)
                } else if (!isUpdate && updateBean == null) {
                    updateBean = CacheGoodsBean()
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = ""
                    updateBean?.categoryGUID = categoryId ?: ""
                    updateBean?.num = selectNum?.div(bean?.bagCount?.toIntOrNull()?:1)?.toString()?:"0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    val zhekou = bean?.zk?.toDoubleOrNull()?.div(100) ?: 0.00
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.times(1.minus(zhekou))?.toString() ?: ""
                    beanDao?.insert(updateBean)
                }

            }

            override fun onCacheOrderBeanMinius(position: Int, selectNum: Int, bean: NewComeProBean?) {
                var loadAll = getCacheGoods()?.filter {
                    it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
                }
                var isUpdate = false
                var updateBean: CacheGoodsBean? = null
                loadAll?.forEachIndexed { index, orderBean ->
                    if (orderBean?.goodNO?.equals(bean?.id ?: "") ?: false) {
                        isUpdate = true
                        updateBean = orderBean
                    }
                }
                if (isUpdate && updateBean != null && selectNum > 0) {
                    updateBean?.goodNO = bean?.id ?: ""
                    updateBean?.companyId = AppContext.get()?.companyId ?: ""
                    updateBean?.customerId = CacheCustomerId ?: ""
                    updateBean?.bz = updateBean?.bz ?: ""
                    updateBean?.categoryGUID = categoryId ?: ""
                    updateBean?.num = selectNum?.div(bean?.bagCount?.toIntOrNull()?:1)?.toString()?:"0"
                    updateBean?.price = bean?.price ?: ""
                    updateBean?.bagCount = bean?.bagCount ?: ""
                    updateBean?.boxCount = bean?.boxCount ?: ""
                    updateBean?.count = bean?.count ?: ""
                    updateBean?.name = bean?.name ?: ""
                    updateBean?.no = bean?.no ?: ""
                    updateBean?.parentGuid = bean?.parentGuid ?: ""
                    updateBean?.url = bean?.url ?: ""
                    updateBean?.xname = bean?.xname ?: ""
                    updateBean?.zk = bean?.zk ?: ""
                    updateBean?.totalPrice = bean?.price?.toDoubleOrNull()?.times(selectNum)?.toString() ?: ""
                    beanDao?.update(updateBean)
                } else if (isUpdate && updateBean != null && selectNum == 0) {
                    beanDao?.delete(updateBean)
                }

            }
        })
        manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                if (xr_toolbar_list?.isHeaderView(position) == true) {
                    Log.d("isHeader", "isHeader  true    $position    type  ")
                    return 2
                } else if (xr_toolbar_list?.isFooterView(position) == true) {
                    return 2
                } else if (xr_toolbar_list?.isEmptyView(mNextAdapter?.itemCount ?: 0) == true) {
                    return 2
                } else {
                    Log.d("isHeader", "isHeader  false    $position    type  ")
                    return 1
                }
            }
        }
    }


    override fun onRefresh() {
        cacheLeftPosion=leftPosion
        cacheRightPosion=rightPosion
        isComeplete = false
        isRefrsesh = true
        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        mNextAdapter?.setCacheData(loadAll)
        if (leftPosion == 0 && rightPosion == 0) {
            loadComPlete()
            return
        }
        if (isRefreshFinishComplete) {
            if (leftPosion == 0 && rightPosion != 0) {
                leftPosion = 0
                rightPosion = rightPosion.minus(1)
            } else {
                if (rightPosion == 0) {
                    leftPosion = leftPosion.minus(1)
                    rightPosion = mDataRight?.getOrNull(leftPosion)?.size?.minus(1) ?: 0
                } else {
                    leftPosion = leftPosion
                    rightPosion = rightPosion.minus(1)

                }
            }
            categoryId = mDataRight?.getOrNull(leftPosion)?.getOrNull(rightPosion)?.guid ?: ""

            menu.outsideMenuClick(leftPosion, rightPosion)
            /*  if (leftPosion == 0 && rightPosion == 0) {
                  loadComPlete()
                  return
              } else {
                  categoryId = mDataRight?.getOrNull(leftPosion)?.getOrNull(rightPosion)?.guid ?: ""

                  menu.outsideMenuClick(leftPosion, rightPosion)
              }*/
        }
        //    mBasePresenter?.getProductList()
    }

    override fun onLoadMore() {
        cacheLeftPosion=leftPosion
        cacheRightPosion=rightPosion
        var loadAll = getCacheGoods()?.filter {
            it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
        }
        mNextAdapter?.setCacheData(loadAll)
        if (isLoadMoreFinish) {
            if (leftPosion == mDataLeft?.size?.minus(1)) {
                if (rightPosion != mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                    leftPosion = mDataLeft?.size?.minus(1) ?: 0
                    rightPosion = rightPosion.plus(1)
                    isComeplete = false
                } else {
                    isComeplete = true
                    loadComPlete()
                    return
                }
            } else {
                isComeplete = false
                if (rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                    leftPosion = leftPosion.plus(1)
                    rightPosion = 0
                } else {
                    leftPosion = leftPosion
                    rightPosion = rightPosion.plus(1)

                }
            }
            categoryId = mDataRight?.getOrNull(leftPosion)?.getOrNull(rightPosion)?.guid ?: ""
            isLoadMoreFinish = false
            menu.outsideMenuClick(leftPosion, rightPosion)

        }
        //   mBasePresenter?.getProductList()
    }

    fun loadComPlete() {
        xr_toolbar_list?.loadMoreComplete()
        xr_toolbar_list?.refreshComplete()
        if (!isComeplete) {
            xr_toolbar_list?.setNoMore(false)
        } else {
            xr_toolbar_list?.setNoMore(true)
        }
        if (isRefrsesh) {
            if (cacheLeftPosion != 0 || cacheRightPosion != 0) {
                xr_toolbar_list?.scrollToPosition(mNextAdapter?.itemCount?.minus(1) ?: 0)
            }
            isRefrsesh = false
        }/* else {
            xr_toolbar_list?.smoothScrollToPosition(0)
        }*/
        cacheLeftPosion=leftPosion
        cacheRightPosion=rightPosion
    }

    override fun getProductListParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
            if (categoryId.checkEmpty()) {
                categoryId = initCategoryId
            }
            put("categoryId", categoryId)
        }
        return Observable.just(map)
    }

    override fun showGoodsList(data: ArrayList<GoodsListBean>) {
        mDataLeft?.clear()
        data.forEach {
            var list: ArrayList<GoodsListBean>? = null
            if (it.level == 0) {
                list = arrayListOf()
                mDataLeft?.add(it)
                mDataRight?.add(list)
            } else if (it.level == 1) {
                mDataRight?.getOrNull(mDataRight?.size?.minus(1) ?: 0)?.add(it)
            }
        }
        menu?.setOnMenuCloseListerner {
            val drawable = resources.getDrawable(R.drawable.ic_arrow_down_red)
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            bt_my_title.setCompoundDrawables(null, null, drawable, null)
        }
        menu.isAutoRefresh = false
        menu.setDifideView(bt_my_title)

        menu.setMenuData(mDataLeft?.map { it.name ?: "" } as? ArrayList<String>
                ?: arrayListOf<String>(), mDataRight?.map {
            val list = it.map { it.name }
            return@map list as? ArrayList<String>
        } as? ArrayList<ArrayList<String>> ?: arrayListOf<ArrayList<String>>())

        ll_product_list_container.removeAllViews()
        ll_product_list_container.addView(menu.dropMenu)
        menu.setTopTapHide()
        //初始化刚进来的时候 新品的categoryId为空 无数据
        initCategoryId = data.getOrNull(0)?.guid ?: ""


        var isRefresh = true
        mDataRight?.forEachIndexed { index, arrayList ->
            var left = index
            arrayList.forEachIndexed { index, goodsListBean ->
                if (goodsListBean.guid.equals(bundleCategoryId)) {
                    isRefresh = false
                    menu?.outsideMenuClick(left, index)
                    return@forEachIndexed
                }
            }
        }
        if (isRefresh) {
            mDataLeft?.forEachIndexed { index, goodsListBean ->
                if (goodsListBean.guid.equals(bundleCategoryId)) {
                    menu?.outsideMenuClick(index, 0)
                }
            }
        }

    }

    override fun <T> showContent(data: T?) {
        try {
            if (data as? ArrayList<NewComeProBean> != null) {
                isRefreshFinishComplete = true
                isLoadMoreFinish = true
                mData?.clear()
                mData?.addAll((data as? ArrayList<NewComeProBean>) ?: arrayListOf())
//                if (isRefrsesh){
//                    smoothPosition=mData?.size?.minus(1)?:0
//                }
                if (mData?.size ?: 0 < 1 && mEmptyView != null) {
                    xr_toolbar_list?.emptyView = mEmptyView
                }
                mNextAdapter?.setData(mData)
                loadComPlete()
                getRefreshText()
                getLoadMoreText()
            }
        } catch (e: Exception) {
            KLog.e(e.message)
        }

    }

    private fun getLoadMoreText() {
        var tempLeft = 0
        var tempRight = 0
        if (leftPosion == mDataLeft?.size?.minus(1)) {
            if (rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                tempLeft = mDataLeft?.size?.minus(1) ?: 0
                tempRight = mDataRight?.getOrNull(leftPosion)?.size?.minus(1) ?: 0
            } else {
                tempLeft = mDataLeft?.size?.minus(1) ?: 0
                tempRight = rightPosion.plus(1)
            }
        } else {
            if (rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1)) {
                tempLeft = leftPosion.plus(1)
                tempRight = 0
            } else {
                tempLeft = leftPosion
                tempRight = rightPosion.plus(1)

            }
        }
        if (leftPosion == mDataLeft?.size?.minus(1) ?: 0 && rightPosion == mDataRight?.getOrNull(leftPosion)?.size?.minus(1) ?: 0) {
            loadMoreText = resources.getString(R.string.str_there_no_data_more)
        } else {
            loadMoreText = mDataRight?.getOrNull(tempLeft)?.getOrNull(tempRight)?.name ?: mDataLeft?.getOrNull(tempLeft)?.name ?: ""
        }
        xr_toolbar_list?.setLoadingMoreText(loadMoreText
                ?: resources.getString(R.string.str_up_slide_load), resources.getString(R.string.str_there_no_data_more), resources.getString(R.string.str_loading_more))
    }

    private fun getRefreshText() {
        var tempLeft = 0
        var tempRight = 0
        if (leftPosion == 0) {
            if (rightPosion == 0) {
                tempLeft = 0
                tempRight = 0
            } else {
                tempLeft = 0
                tempRight = rightPosion.minus(1)
            }
        } else {
            if (rightPosion == 0) {
                tempLeft = leftPosion.minus(1)
                tempRight = mDataRight?.getOrNull(tempLeft)?.size?.minus(1) ?: 0
            } else {
                tempLeft = leftPosion
                tempRight = rightPosion.minus(1)

            }

        }
        if (leftPosion == 0 && rightPosion == 0) {
            refreshTextText = resources.getString(R.string.str_there_no_data_more)
        } else {
            refreshTextText = mDataRight?.getOrNull(tempLeft)?.getOrNull(tempRight)?.name ?: mDataLeft?.getOrNull(tempLeft)?.name ?: ""

        }
        xr_toolbar_list?.setRefreshText(refreshTextText
                ?: resources.getString(R.string.str_down_slide_load), refreshTextText
                ?: resources.getString(R.string.str_release_and_refresh_immediately), resources.getString(R.string.str_refreshing), resources.getString(R.string.str_load_complete))


    }

    override fun showError(e: Throwable?) {
        KLog.e(e?.message)
        isRefreshFinishComplete = true
        isLoadMoreFinish = true
        if (mErrorView != null) {
            xr_toolbar_list?.emptyView = mErrorView
            mErrorView?.setOnClickListener {
                mBasePresenter?.getProductList()
            }
        }
        mNextAdapter?.setData(arrayListOf())
        loadComPlete()
    }

    override fun getRequestParams(): Observable<Map<String, Any>> {
        val map = ArrayMap<String, String>().apply {
            put("companyId", AppContext.get().companyId)
        }
        return Observable.just(map)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == 200 && data != null) {
            val jsonStr = data?.getStringExtra("isBackData") ?: ""
            if (leftPosion != data?.getIntExtra("leftPosion", 0) ||
                    rightPosion != data?.getIntExtra("rightPosion", 0)) {
                leftPosion = data?.getIntExtra("leftPosion", 0) ?: 0
                rightPosion = data?.getIntExtra("rightPosion", 0) ?: 0
                mBackData = AppContext.gson()?.fromJson<ArrayList<NewComeProBean>>(jsonStr)
                menu?.outsideMenuClick(leftPosion, rightPosion)
            } else {
                mNextAdapter?.setCacheData(getCacheGoods()?.filter {
                    it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
                })
                mNextAdapter?.notifyDataSetChanged()
            }

        } else if (requestCode == 300 && resultCode == 500) {
            mNextAdapter?.setCacheData(getCacheGoods()?.filter {
                it.companyId?.equals(AppContext.get().companyId ?: "") ?: false
            })
            mNextAdapter?.notifyDataSetChanged()

        }
    }

}
